import React, {Component} from 'react';
import ThePagination from "@/components/ThePagination";
import {Select, Tabs} from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import {
    apiStockLibraryGoodsList,
    apiStockLibraryGoodsPage,
    apiStockTakeListAddBefore,
    apiStockTakeListDel,
    apiStockTakeListPage
} from '@/request/storageManager/stock.js'
import {exportSheetTable} from '@/utils/exportTable'
import './components/style.scss'
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"

const {TabPane} = Tabs;
const {Option} = Select
const status = [{label: '草稿', value: 0, color: 'black'}, {
    label: '未审核',
    value: 1,
    color: "orange"
}, {label: '已审核', value: 2, color: "#1890ff"}, {label: '已驳回', value: 3, color: "#cccccc"}]

class Stock extends Component {
    constructor() {
        super()
        this.queryFormRef_store = React.createRef()
        this.state = {
            columns: [
                {
                    title: "序号",
                    dataIndex: "index",
                    key: "index",
                    render: (text, record, index) => {
                        return ((this.state.pageData.pageNo - 1) * (this.state.pageData.pageSize) + (index + 1));
                    }
                },
                {
                    title: "仓库名称",
                    dataIndex: "libraryName",
                    key: "libraryName",

                },
                {
                    title: "物料编码",
                    dataIndex: "goodsSkuNo",
                    key: "goodsSkuNo",

                },
                {
                    title:'物料名称',
                    dataIndex:'materialName',
                    key:'materialName',
                },
                {
                    title: "商品名称",
                    dataIndex: "goodsName",
                    key: "goodsName",

                },
                {
                    title: "规格",
                    dataIndex: "sku",
                    key: "sku",

                },

                {
                    title: "库存下限",
                    dataIndex: "minCount",
                    key: "minCount",
                    render: (text) => {
                        if (text == -1) {
                            return '不限制'
                        }
                        return text
                    }
                },
                {
                    title: "上下架",
                    dataIndex: "goodsStatus",
                    key: "goodsStatus",
                    render: (text) => {
                        switch (text) {
                            case 'Y':
                                return "上架"
                            case 'N':
                                return "下架"
                            case 'G':
                                return "管理员下架"
                            default:
                                return '/'
                        }
                    }

                },
                {
                    title: "库存量",
                    dataIndex: "count",
                    key: "count",

                },
                {
                    title: "待出库",
                    dataIndex: "waiteOutCount",
                    key: "waiteOutCount",

                },
                {
                    title: "平均价",
                    dataIndex: "price",
                    key: "price",
                    render: (text, record) => {
                        return record.price >= 0 ? ((record.price) / 100).toFixed(2) : "-"
                    }
                },
                {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    fixed: 'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['storage:stockStore:view']}
                                       onClick={() => this.goGoods(render.id)}>查看详情</TheButton>
                        </div>
                    }
                },
            ],
            newColumns_store: [],
            form_show_store: true,
            searchOption_store: [
                {
                    field: 'libraryId',
                    label: '仓库名称',
                    placeholder: '请选择仓库名称',
                    required: false,
                    rules: [],
                    type: 'Select',
                    txt: 'name',
                    value: 'id',
                    options: [],
                    defaultValue: ''
                },
                {
                    field: 'goodsStatus',
                    label: '上架状态',
                    placeholder: '请选择上架状态',
                    required: false,
                    rules: [],
                    type: 'Select',
                    options: [
                        {label: "上架", value: "Y"}, {label: "下架", value: "N"}
                    ],
                    defaultValue: ''
                },
                {
                    field: 'materialId',
                    label: '物料ID',
                    placeholder: '请输入物料ID',
                    required: false,
                    rules: [],
                    type: 'Input',
                    defaultValue: ''
                },
                {
                    field: 'goodsName',
                    label: '物品名称',
                    placeholder: '请输入物品名称',
                    required: false,
                    rules: [],
                    type: 'Input',
                    defaultValue: ''
                },

            ],
            queryForm_store: {},
            dataSource: [],
            totalStore: 0,
            goodsName_store: '',
            libraryId_store: '',
            librarys: [],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
        }
    }

    componentDidMount() {
        this.setState({
            newColumns_store: this.state.columns
        })
        let searchParams = store.getState().searchValue
        let {queryForm_store, pageNo, pageSize, pathName} = searchParams

        this.queryFormRef_store.onSetDefault({
            ...queryForm_store
        })

        if (searchParams &&pageNo &&pathName == 'store') {
            this.setState({
                queryForm_store,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                },
            }, () => {
                this.getLibrarys()
                this.getPage()
            })
        } else {
            this.getLibrarys()
            this.getPage()
        }
    }

    goGoods(id) {
        this.props.history.push('/stockManager/store/' + id)
    }

    async getLibrarys() {
        let res = await apiStockTakeListAddBefore()
        if (res.code === 0) {
            // console.log(res.data.librarys);
            this.state.searchOption_store[0].options = res.data.librarys
            this.setState({
                librarys: res.data.librarys,
                searchOption_store: this.state.searchOption_store
            })
        }
    }

    // 库存
    getPage(values) {
        this.setState({
            queryForm_store: values === undefined ? this.state.queryForm_store : {...values}
        }, async () => {
            let {pageNo, pageSize} = this.state.pageData
            let params = {
                pageNo: this.state.pageData.pageNo,
                pageSize: this.state.pageData.pageSize,
                queryForm_store: this.state.queryForm_store,
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'store',
                    ...params
                }
            })
            let res = await apiStockLibraryGoodsPage({pageNo, pageSize, ...this.state.queryForm_store})
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    totalStore: res.totalCount
                })
            }
        })
    }

    pageChangeStore = (pageNo, pageSize) => {
        this.setState({
            // goodsName_store: values.goodsName ? values.goodsName : '',
            // libraryId_store: values.libraryId ? values.libraryId : '',
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getPage()
        })
    };

    onReset_store = () => {
        this.setState({
            queryForm_store: {}
        }, () => {
            this.pageChangeStore(1, 10)
        })
    }

    async del(id) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiStockTakeListDel({id})
                if (res.code === 0) {
                    this.pageChangeCheck(1, 10)
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }
            }
        });

    }

    getGoodsStatus = (value) => {
        switch (value) {
            case 'Y':
                return "上架"
            case 'N':
                return "下架"
            case 'G':
                return "管理员下架"
            default:
                return '/'
        }
    }

    export = async () => {
        let tH_data, tB_data
        tH_data = [
            {prop: 'libraryName', title: '仓库名称'},
            {prop: 'goodsSkuNo', title: '物料编码'},
            {prop: 'materialName', title:'物料名称'},
            {prop: 'goodsName', title: '商品名称'},
            {prop: 'sku', title: '规格'},
            {prop: 'goodsStatus', title: '上架状态'},
            {prop: 'minCount', title: '库存下限', valueType:'number'},
            {prop: 'count', title: '库存量', valueType:'number'},
            {prop: 'waiteOutCount', title: '待出库', valueType:'number'},
        ]
        let values = this.state.queryForm_store
        console.log(values);
        let res = await apiStockLibraryGoodsList({
            "goodsName": values && values.goodsName ? values.goodsName : '',
            libraryId: values && values.libraryId ? values.libraryId : '',
            materialId: values && values.materialId ? values.materialId : "",
            goodsStatus: values && values.goodsStatus ? values.goodsStatus : ""
        })
        if (res.code === 0 && res.data && res.data.length > 0) {
            tB_data = res.data.map(item => {
                return {
                    ...item,
                    goodsStatus: this.getGoodsStatus(item.goodsStatus),
                    minCount: item.minCount == -1 ? '不限制' : item.minCount,
                    row_bgColor: item.count < item.minCount ? '#e8b300' : ''
                }
            })
            exportSheetTable({
                fileName: '库存管理', tH_data, tB_data: tB_data, isSheet: true, merge: false
            })
        }

    }

    rowClassName(record, index) {

        if (record.minCount > record.count) {
            return 'warning'
        }
        return ''
    }

    onChange(e) {
        let params = {
            tab: e
        }
        store.dispatch({
            type: 'SavePageTabValue',
            data: {
                ...params
            }
        })

        this.queryFormRef_store.onSetDefault({
            ...this.state.queryForm_store
        })
    }

    onFormSearch_store(values) {
        this.setState({
            pageData: {pageNo: 1, pageSize: 10}
        }, () => {
            this.getPage(values)
        })
    }

    render() {
        let {
            columns, dataSource, pageData,
            librarys, totalStore,
            form_show_store, searchOption_store, newColumns_store
        } = this.state
        return (
            <div className="p-layout-box commodity-examine">
                <TheQueryForm ref={(ref) => this.queryFormRef_store = ref} show={form_show_store}
                              option={searchOption_store}
                              onReset={() => this.onReset_store()}

                              onGetValues={(values) => this.onFormSearch_store(values)}>
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({form_show_store: !this.state.form_show_store})}
                    onTableRefresh={() => this.getPage()}
                    onColumnsFilter={(value) => this.setState({
                        newColumns_store: value
                    })}
                >
                    <TheButton type="default" size="middle" haspermi={['storage:stockStore:export']}
                               onClick={this.export}>库存导出</TheButton>
                </TheTableExtend>
                <TheTable
                    scroll={{x: "max-content", y: '63vh'}}
                    columns={newColumns_store}
                    rowClassName={(record, index) => this.rowClassName(record, index)}
                    dataSource={dataSource}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={totalStore}
                    pageChange={this.pageChangeStore}
                />
            </div>
        );
    }
}

export default Stock
